using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.Common.Results;
using ERP.ERPSystem.WarehouseManagement;
using ERP.ERPSystem.WarehouseManagement.Dto;
using ERP.Team.WarehouseManagement;
using ERP.Team.ProductionSystem;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace ERP.Application.ERPSystem.WarehouseManagement
{
    /// <summary>
    /// 供应商退货服务实现
    /// </summary>
    public class SupplierReturnsServices : ApplicationService, ISupplierReturnsServices
    {
        private readonly IRepository<SupplierReturns, int> _supplierReturnsRepository;
        private readonly IRepository<Supplier, int> _supplierRepository;
        private readonly IRepository<MaterialproductModel, int> _materialProductRepository;

        public SupplierReturnsServices(
            IRepository<SupplierReturns, int> supplierReturnsRepository,
            IRepository<Supplier, int> supplierRepository,
            IRepository<MaterialproductModel, int> materialProductRepository)
        {
            _supplierReturnsRepository = supplierReturnsRepository;
            _supplierRepository = supplierRepository;
            _materialProductRepository = materialProductRepository;
        }

        /// <summary>
        /// 获取供应商列表（用于选择）
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<SupplierPagedResult>> GetSuppliersAsync(string keyword = null, int pageNumber = 1, int pageSize = 10)
        {
            try
            {
                var queryable = await _supplierRepository.GetQueryableAsync();

                // 应用搜索条件
                if (!string.IsNullOrEmpty(keyword))
                {
                    queryable = queryable.Where(x => 
                        x.SupplierCode.Contains(keyword) || 
                        x.SupplierName.Contains(keyword));
                }

                // 只查询启用的供应商
                queryable = queryable.Where(x => x.IsNo == 1);

                // 获取总数
                var totalCount = queryable.Count();

                // 分页和排序
                var pagedData = queryable
                    .OrderByDescending(x => x.Id)
                    .Skip((pageNumber - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();

                // 转换为DTO
                var pageData = pagedData.Select(entity => new SupplierSelectDto
                {
                    Id = entity.Id,
                    SupplierCode = entity.SupplierCode,
                    SupplierName = entity.SupplierName,
                    SupplierNickname = entity.SupplierName, // 使用供应商名称作为简称
                    SupplierGrade = entity.SupplierGrade,
                    SupplierScore = entity.SupplierScore,
                    SupplierPhone = entity.SupplierPhone,
                    IsNo = entity.IsNo,
                    Context = entity.Context
                }).ToList();

                var result = new SupplierPagedResult
                {
                    Items = pageData,
                    TotalCount = totalCount,
                    PageNumber = pageNumber,
                    PageSize = pageSize
                };

                return APIResult<SupplierPagedResult>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<SupplierPagedResult>.CreateError("查询供应商列表失败");
            }
        }

        /// <summary>
        /// 根据供应商编码获取供应商信息
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<SupplierSelectDto>> GetSupplierByCodeAsync(string supplierCode)
        {
            try
            {
                if (string.IsNullOrEmpty(supplierCode))
                {
                    return APIResult<SupplierSelectDto>.CreateError("供应商编码不能为空");
                }

                var entity = await _supplierRepository.FirstOrDefaultAsync(x => x.SupplierCode == supplierCode);
                if (entity == null)
                {
                    return APIResult<SupplierSelectDto>.CreateError("供应商不存在");
                }

                var result = new SupplierSelectDto
                {
                    Id = entity.Id,
                    SupplierCode = entity.SupplierCode,
                    SupplierName = entity.SupplierName,
                    SupplierNickname = entity.SupplierName,
                    SupplierGrade = entity.SupplierGrade,
                    SupplierScore = entity.SupplierScore,
                    SupplierPhone = entity.SupplierPhone,
                    IsNo = entity.IsNo,
                    Context = entity.Context
                };

                return APIResult<SupplierSelectDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<SupplierSelectDto>.CreateError("查询供应商信息失败");
            }
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<SupplierReturnsPagedResult>> GetPagedListAsync(SupplierReturnsQueryDto query)
        {
            try
            {
                var queryable = await _supplierReturnsRepository.GetQueryableAsync();

                // 应用查询条件
                if (!string.IsNullOrEmpty(query.ReturnCode))
                {
                    queryable = queryable.Where(x => x.ReturnCode.Contains(query.ReturnCode));
                }

                if (!string.IsNullOrEmpty(query.ReturnName))
                {
                    queryable = queryable.Where(x => x.ReturnName.Contains(query.ReturnName));
                }

                if (!string.IsNullOrEmpty(query.ProcurementCode))
                {
                    queryable = queryable.Where(x => x.ProcurementCode.Contains(query.ProcurementCode));
                }

                if (!string.IsNullOrEmpty(query.Vendor))
                {
                    queryable = queryable.Where(x => x.Vendor.Contains(query.Vendor));
                }

                if (!string.IsNullOrEmpty(query.LotNumber))
                {
                    queryable = queryable.Where(x => x.LotNumber.Contains(query.LotNumber));
                }

                if (query.StartReturnDate.HasValue)
                {
                    queryable = queryable.Where(x => x.ReturnDate >= query.StartReturnDate.Value);
                }

                if (query.EndReturnDate.HasValue)
                {
                    queryable = queryable.Where(x => x.ReturnDate <= query.EndReturnDate.Value);
                }

                if (query.DocumentStatus.HasValue)
                {
                    queryable = queryable.Where(x => x.DocumentStatus == query.DocumentStatus.Value);
                }

                // 获取总数
                var totalCount = queryable.Count();

                // 分页和排序
                var pagedData = queryable
                    .OrderByDescending(x => x.Id)
                    .Skip((query.PageNumber - 1) * query.PageSize)
                    .Take(query.PageSize)
                    .ToList();

                // 转换为DTO
                var pageData = pagedData.Select(entity => new SupplierReturnsDto
                {
                    Id = entity.Id,
                    ReturnCode = entity.ReturnCode,
                    ReturnName = entity.ReturnName,
                    ProcurementCode = entity.ProcurementCode,
                    Vendor = entity.Vendor,
                    LotNumber = entity.LotNumber,
                    ReturnDate = entity.ReturnDate,
                    DocumentStatus = entity.DocumentStatus,
                    MaterielCode = entity.MaterielCode,
                    CreateTime = entity.CreationTime,
                    UpdateTime = entity.LastModificationTime
                }).ToList();

                var result = new SupplierReturnsPagedResult
                {
                    Items = pageData,
                    TotalCount = totalCount,
                    PageNumber = query.PageNumber,
                    PageSize = query.PageSize
                };

                return APIResult<SupplierReturnsPagedResult>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<SupplierReturnsPagedResult>.CreateError("查询供应商退货列表失败");
            }
        }

        /// <summary>
        /// 根据ID获取详情
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<SupplierReturnsDto>> GetByIdAsync(int id)
        {
            try
            {
                var entity = await _supplierReturnsRepository.FirstOrDefaultAsync(x => x.Id == id);

                if (entity == null)
                {
                    return APIResult<SupplierReturnsDto>.CreateError("供应商退货不存在");
                }

                var result = new SupplierReturnsDto
                {
                    Id = entity.Id,
                    ReturnCode = entity.ReturnCode,
                    ReturnName = entity.ReturnName,
                    ProcurementCode = entity.ProcurementCode,
                    Vendor = entity.Vendor,
                    LotNumber = entity.LotNumber,
                    ReturnDate = entity.ReturnDate,
                    DocumentStatus = entity.DocumentStatus,
                    MaterielCode = entity.MaterielCode,
                    ConcurrencyStamp = entity.ConcurrencyStamp,
                    CreateTime = entity.CreationTime,
                    UpdateTime = entity.LastModificationTime
                };

                return APIResult<SupplierReturnsDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<SupplierReturnsDto>.CreateError("获取供应商退货详情失败");
            }
        }

        /// <summary>
        /// 创建供应商退货
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<SupplierReturnsDto>> CreateAsync(SupplierReturnsCreateDto createDto)
        {
            try
            {
                // 检查退货单编号是否已存在
                var existingEntity = await _supplierReturnsRepository.FirstOrDefaultAsync(x => x.ReturnCode == createDto.ReturnCode);
                if (existingEntity != null)
                {
                    return APIResult<SupplierReturnsDto>.CreateError("退货单编号已存在");
                }

                // 创建新实体
                var entity = new SupplierReturns(
                    createDto.ReturnCode,
                    createDto.ReturnName,
                    createDto.ProcurementCode,
                    createDto.Vendor,
                    createDto.LotNumber,
                    createDto.ReturnDate,
                    createDto.DocumentStatus);

                // 设置物料编码
                entity.MaterielCode = createDto.MaterielCode;

                var savedEntity = await _supplierReturnsRepository.InsertAsync(entity, autoSave: true);

                // 转换为DTO
                var result = new SupplierReturnsDto
                {
                    Id = savedEntity.Id,
                    ReturnCode = savedEntity.ReturnCode,
                    ReturnName = savedEntity.ReturnName,
                    ProcurementCode = savedEntity.ProcurementCode,
                    Vendor = savedEntity.Vendor,
                    LotNumber = savedEntity.LotNumber,
                    ReturnDate = savedEntity.ReturnDate,
                    DocumentStatus = savedEntity.DocumentStatus,
                    MaterielCode = savedEntity.MaterielCode,
                    ConcurrencyStamp = savedEntity.ConcurrencyStamp,
                    CreateTime = savedEntity.CreationTime,
                    UpdateTime = savedEntity.LastModificationTime
                };

                return APIResult<SupplierReturnsDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<SupplierReturnsDto>.CreateError("创建供应商退货失败");
            }
        }

        /// <summary>
        /// 更新供应商退货
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<SupplierReturnsDto>> UpdateAsync(SupplierReturnsUpdateDto updateDto)
        {
            try
            {
                // 从数据库获取实体
                var entity = await _supplierReturnsRepository.GetAsync(updateDto.Id);
                if (entity == null)
                {
                    return APIResult<SupplierReturnsDto>.CreateError("供应商退货不存在");
                }

                // 检查退货单编号是否被其他记录使用
                var existingEntity = await _supplierReturnsRepository.FirstOrDefaultAsync(x => x.ReturnCode == updateDto.ReturnCode && x.Id != updateDto.Id);
                if (existingEntity != null)
                {
                    return APIResult<SupplierReturnsDto>.CreateError("退货单编号已被其他记录使用");
                }

                // 设置并发标记
                entity.ConcurrencyStamp = updateDto.ConcurrencyStamp;
                
                // 更新实体数据
                entity.ReturnCode = updateDto.ReturnCode;
                entity.ReturnName = updateDto.ReturnName;
                entity.ProcurementCode = updateDto.ProcurementCode;
                entity.Vendor = updateDto.Vendor;
                entity.LotNumber = updateDto.LotNumber;
                entity.ReturnDate = updateDto.ReturnDate;
                entity.DocumentStatus = updateDto.DocumentStatus;
                entity.MaterielCode = updateDto.MaterielCode;

                // 保存到数据库
                var updatedEntity = await _supplierReturnsRepository.UpdateAsync(entity, autoSave: true);

                // 转换为DTO
                var result = new SupplierReturnsDto
                {
                    Id = updatedEntity.Id,
                    ReturnCode = updatedEntity.ReturnCode,
                    ReturnName = updatedEntity.ReturnName,
                    ProcurementCode = updatedEntity.ProcurementCode,
                    Vendor = updatedEntity.Vendor,
                    LotNumber = updatedEntity.LotNumber,
                    ReturnDate = updatedEntity.ReturnDate,
                    DocumentStatus = updatedEntity.DocumentStatus,
                    MaterielCode = updatedEntity.MaterielCode,
                    ConcurrencyStamp = updatedEntity.ConcurrencyStamp,
                    CreateTime = updatedEntity.CreationTime,
                    UpdateTime = updatedEntity.LastModificationTime
                };

                return APIResult<SupplierReturnsDto>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<SupplierReturnsDto>.CreateError("更新供应商退货失败");
            }
        }

        /// <summary>
        /// 删除供应商退货
        /// </summary>
        [UnitOfWork]
        public async Task<OperationResult> DeleteAsync(int id)
        {
            try
            {
                // 从数据库删除
                await _supplierReturnsRepository.DeleteAsync(id);
                return OperationResult.SuccessResult("删除成功");
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return OperationResult.ErrorResult("删除供应商退货失败");
            }
        }

        /// <summary>
        /// 批量删除供应商退货
        /// </summary>
        [UnitOfWork]
        public async Task<OperationResult> BatchDeleteAsync(List<int> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    return OperationResult.ErrorResult("请选择要删除的记录");
                }

                // 批量删除
                foreach (var id in ids)
                {
                    await _supplierReturnsRepository.DeleteAsync(id);
                }

                return OperationResult.SuccessResult($"批量删除成功，共删除{ids.Count}条记录");
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return OperationResult.ErrorResult("批量删除供应商退货失败");
            }
        }

        /// <summary>
        /// 获取物料产品列表（用于供应商退货物料选择）
        /// </summary>
        [UnitOfWork]
        public async Task<APIResult<MaterialProductPagedResult>> GetMaterialProductsAsync(string keyword = null, int pageNumber = 1, int pageSize = 10)
        {
            try
            {
                var queryable = await _materialProductRepository.GetQueryableAsync();

                // 应用搜索条件
                if (!string.IsNullOrEmpty(keyword))
                {
                    queryable = queryable.Where(x => 
                        x.MaterielCode.Contains(keyword) || 
                        x.MaterielName.Contains(keyword) ||
                        x.Specifications.Contains(keyword));
                }

                // 只查询启用的物料产品
                queryable = queryable.Where(x => x.IsNo == 1);

                // 获取总数
                var totalCount = queryable.Count();

                // 分页和排序
                var pagedData = queryable
                    .OrderByDescending(x => x.Id)
                    .Skip((pageNumber - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();

                // 转换为DTO
                var pageData = pagedData.Select(entity => new MaterialProductSelectDto
                {
                    Id = entity.Id,
                    MaterielCode = entity.MaterielCode,
                    MaterielName = entity.MaterielName,
                    MaterielUrl = entity.MaterielUrl,
                    Specifications = entity.Specifications,
                    UnitsId = entity.UnitsId,
                    MaterielTypePid = entity.MaterielTypePid,
                    MaterielTypeId = entity.MaterielTypeId,
                    IsNo = entity.IsNo,
                    IsSecure = entity.IsSecure,
                    CreateTime = entity.CreateTime
                }).ToList();

                var result = new MaterialProductPagedResult
                {
                    Items = pageData,
                    TotalCount = totalCount,
                    PageNumber = pageNumber,
                    PageSize = pageSize
                };

                return APIResult<MaterialProductPagedResult>.CreateSuccess(result);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return APIResult<MaterialProductPagedResult>.CreateError("查询物料产品列表失败");
            }
        }
    }
} 